package com.qianbei.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : pipi
 *     e-mail : xxx@xx
 *     time   : 2019/01/14
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class DeleteFileService extends IntentService {
    private List<String> imgPath = new ArrayList<>();
    private static String[] imageFormat = new String[]{"jpg", "png", "jpeg"};
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public DeleteFileService() {
        super("DeleteFileService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String url = Environment.getExternalStorageDirectory().toString();
        getSdCardImgFile(url+"/qianbei");
        getSdCardImgFile(url+"/DCIM");
        for (String path : imgPath) {
            getContentResolver().delete(Media.EXTERNAL_CONTENT_URI, Media.DATA + "=?", new String[]{path});
        }
    }
    private boolean isImageFile(String path) {
        File file = new File(path);
        long lastModified = file.lastModified();
        long nowTimes = System.currentTimeMillis();
        for (String format : imageFormat) {
            if (path.contains(format) && nowTimes - lastModified >= 7L * 24 * 60 * 60 * 1000) {                                 //如果文件名字包含定义的格式后缀，则返回true
                return true;
            }
        }
        return false;
    }

    private void getSdCardImgFile(String url) {
        File files = new File(url);
        if (!files.exists()) {
            return;
        }
        File[] file = files.listFiles();
        if (file==null) {
            return;
        }
        for (File f : file) {
            if (f.isDirectory()) {
                getSdCardImgFile(f.getAbsolutePath());
            } else {
                if (isImageFile(f.getPath())) {
                    imgPath.add(f.getAbsolutePath());
                }
            }
        }
    }
}
